import request from '@/utils/request'
import authRouter from '@/router/authRouter'
import router from '@/router'
import { createStore } from 'vuex'

// 数据持久化
let userInfo:any = localStorage.getItem('userInfo')
try{
    userInfo = JSON.parse(String(userInfo)) || {}
}catch(err){
    userInfo = null
}

// 创建一个新的 store 实例
 const store = createStore({
    state(){
        return {
            userInfo,
        }
    },
    getters:{
        isLogin(state){
            return state.userInfo?.username
        }
    },
    mutations:{
        login(state,payload){
            state.userInfo = payload
            localStorage.setItem('userInfo',JSON.stringify(payload))
            router.addRoute(authRouter)
        },
        logout(state){
            state.userInfo = null
            localStorage.removeItem('userInfo')
        },
    },
    actions:{
        async login(context,payload){
            // context: 一个与store一样拥有相同属性的对象
            // 发起ajax请求
            const {data} = await request.get('/user/login',{
                params:payload
            })

            // 异步请求数据回来后，修改state（触发mutation）
            context.commit('login',data.data)

            return data;
        }
    }
  })

  export default store;